<script setup lang="ts">
import {computed, onMounted, ref} from 'vue'
// import type { OrderPreResult } from '@/types/order'

import {getPayProducts} from "@/api/products";
import type {CreateOrder} from "@/api/orders/types";
import {createPayOrders} from "@/api/orders";
import type {PayProductsData} from "@/api/products/types";
import {publicUrl} from "@/stores";
import {onLoad} from "@dcloudio/uni-app";
import {htmlEscape} from "@/utils/codeConversion";
// import { useAddressStore } from '@/stores/modules/address'
// import type { AddressItem } from '@/types/address'
// import { getMemberAddressAPI } from '@/services/address/address'

// 获取屏幕边界到安全区域距离
const {safeAreaInsets} = uni.getSystemInfoSync()
// // 订单备注
const buyerMessage = ref('')
// 配送时间
const deliveryList = ref([
  {type: 1, text: '时间不限 (周一至周日)'},
  {type: 2, text: '工作日送 (周一至周五)'},
  {type: 3, text: '周末配送 (周六至周日)'},
])
// 当前配送时间下标
const activeIndex = ref(0)
// 当前配送时间
const activeDelivery = computed(() => deliveryList.value[activeIndex.value])
// 修改配送时间
const onChangeDelivery: UniHelper.SelectorPickerOnChange = (ev) => {
  activeIndex.value = ev.detail.value
}

//
// const address = ref<AddressItem>()
// const selectAddressList = ref<AddressItem[]>()

// 获取订单数据
const orderPre = ref<PayProductsData>()
const getOrderPreData = async () => {
  if (query.count && query.skuId) {
    getPayProducts(query.skuId).then(res => {
      orderPre.value = res.data
      if (orderPre.value.description != null) {
        orderPre.value.description = htmlEscape(orderPre.value.description)
      }
      currentItem.value.orderItems = []
      currentItem.value.orderItems.push({
        product: orderPre.value,
        quantity: query.count,
        price: orderPre.value?.price,
        subtotal: Number(orderPre.value.price) * Number(query.count),
      })
      if (!orderPre.value) {
        uni.showToast({icon: 'none', title: '没有商品'})
        return uni.redirectTo({url: '/pages/home/home'})
      }
    })

  } else if (query.orderId) {
    // 再次购买
    const res = await getPayProducts(query.orderId)
    orderPre.value = res.data
  }
}

// const addressStore = useAddressStore()

// let selectAddress = computed(() => {
//   return (
//     addressStore.selectAddress ||
//     orderPre.value?.userAddresses.find((v) => {
//       v.isDefault
//     })
//   )
// })

// 页面参数
const query = defineProps<{
  skuId?: string
  count?: number
  addressId?: string
  orderId?: string
}>()

const currentItem = ref<CreateOrder>({})
// const selectedAddress = ref('') // 选中的地址ID
const orderId = ref("")
const index = ref(0)
const addresses = ref([
  {id: '1', label: '地址1', fullLocation: '广东省深圳市南山区'},
  {id: '2', label: '地址2', fullLocation: '广东省深圳市福田区'},
  {id: '3', label: '地址3', fullLocation: '广东省深圳市龙岗区'}
]) // 地址列表

const selectedAddressLabel = (e: any) => {
  currentItem.value.shippingAddress = addresses.value[e.detail.value]?.fullLocation
  console.log('picker发送选择改变，携带值为', e.detail.value, addresses.value[e.detail.value])

  index.value = e.detail.value
  // return selected ? selected.label : '未选择地址'
}

// 提交订单
const onOrderSubmit = async () => {
  console.log("当前订单",currentItem.value)
  if (currentItem.value.orderItems) {
    currentItem.value.amount = currentItem.value.orderItems[0].price! * currentItem.value!.orderItems[0].quantity!
    currentItem.value.orderItems[0].productId = currentItem.value.orderItems![0].product!.id!
    // currentItem.value.orderItems[0].subtotal = currentItem.value.orderItems[0].price! * currentItem.value!.orderItems[0].quantity!
  }
  // currentItem.value.shippingAddress = selectedAddress.value
  currentItem.value.currencyType = "10"
  currentItem.value.orderType = "20"
  currentItem.value.orderStatus = "0"


  createPayOrders(currentItem.value).then(async res => {
    if (res.data) {
      uni.showToast({icon: 'success', title: '下单成功'})
      // ElMessage.success("下单成功")
      orderId.value = res.data
      // 关闭当前页面，跳转到订单详情，传递订单id
      await uni.redirectTo({url: `/pagesOrder/detail/detail?id=${res.data}`})
      // paymentDialogVisible.value = true
    } else {
      uni.showToast({icon: 'error', title: '下单失败'})
      // ElMessage.error("下单失败")
    }
  }).catch(() => {
    uni.showToast({icon: 'error', title: '下单失败'})
    // ElMessage.error("下单失败")
  })
  // 没有收货地址提醒
  // if (!selectAddress.value?.id) {
  //   return uni.showToast({ icon: 'none', title: '请选择收货地址' })
  // }


}

onLoad(() => {
  getOrderPreData()
})
</script>

<template>
  <scroll-view scroll-y="true" class="viewport">
    <!-- 收货地址 -->
    <view
        class="shipment"
        hover-class="none"
    >
      <picker @change="selectedAddressLabel" :value="index" :range="addresses">
        <view class="uni-input">{{ addresses[index].fullLocation }}</view>
      </picker>
      <!--      <view class="user"> {{ addresses.receiver }} {{ selectAddress.contact }}</view>-->
      <!--      <view class="address"> {{ addresses.fullLocation }} {{ addresses.address }}</view>-->
      <text class="icon icon-right"></text>
    </view>
    <!--    <view-->
    <!--        v-else-->
    <!--        class="shipment"-->
    <!--        hover-class="none"-->
    <!--    >-->
    <!--      <view class="address"> 请选择收货地址</view>-->
    <!--      <text class="icon icon-right"></text>-->
    <!--    </view>-->

    <!-- 商品信息 -->
    <view class="goods">
      <navigator

          :key="orderPre?.id"
          :url="`/pages/goods/goods?id=${orderPre?.id}`"
          class="item"
          hover-class="none"
      >
        <image class="picture" :src="publicUrl+orderPre?.photo"/>
        <view class="meta">
          <view class="name ellipsis">{{ orderPre?.name }}</view>
          <view class="attrs">x{{ query.count }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ orderPre?.price?.toFixed(2) }}</view>
            <view class="price symbol">{{ ((orderPre?.price || 0) * 1.1).toFixed(2) }}</view>
          </view>
          <view class="count">{{ (Number(orderPre?.price) * Number(query.count)).toFixed(2) }}</view>
        </view>
      </navigator>
    </view>

    <!-- 配送及支付方式 -->
    <view class="related">
      <view class="item">
        <text class="text">配送时间</text>
        <picker :range="deliveryList" range-key="text" @change="onChangeDelivery">
          <view class="icon-fonts picker">{{ activeDelivery.text }}</view>
        </picker>
      </view>
      <view class="item">
        <text class="text">订单备注</text>
        <input
            class="input"
            :cursor-spacing="30"
            placeholder="选题，建议留言前先与商家沟通确认"
            v-model="buyerMessage"
        />
      </view>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价:</text>
        <text class="number symbol">{{ (Number(orderPre?.price) * Number(query.count)).toFixed(2) }}</text>
      </view>
      <view class="item">
        <text class="text">运费:</text>
        <text class="number symbol">包邮</text>
      </view>
    </view>
  </scroll-view>

  <!-- 吸底工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="total-pay symbol">
      <text class="number">{{ (Number(orderPre?.price) * Number(query.count)).toFixed(2) }}</text>
    </view>
    <view class="button" @tap="onOrderSubmit">
      提交订单
    </view>
  </view>
</template>

<style scoped lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png) 20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #27ba9b;
  }

  .disabled {
    opacity: 0.6;
  }
}
</style>
